package com.bwda.dsrs.systemservice.service.impl;

import com.bwda.dsrs.systemservice.domain.condition.emailsettting.EmailContentCondition;
import com.bwda.dsrs.systemservice.domain.po.emailsettting.EmailSetttingPo;
import com.bwda.dsrs.systemservice.service.IMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @description:
 * @author: yangjun
 * @create: 2019-09-02 15:14
 */
@Service
public class MailServiceImpl implements IMailService {
    private static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);


    public MimeMessagePreparator send(EmailSetttingPo emailSetttingPo, EmailContentCondition emailContentCondition) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
                message.setTo(emailContentCondition.getTo());
                message.setFrom(emailSetttingPo.getAddress());
                message.setSubject(emailContentCondition.getSubject());
                if (emailContentCondition.getAttachmentList() != null && !emailContentCondition.getAttachmentList().isEmpty()) {
                    message.setText(emailContentCondition.getText(), true);
                    for (String path : emailContentCondition.getAttachmentList()) {
                        FileSystemResource file = new FileSystemResource(new File(path));
                        String fileName = file.getFilename();
                        //添加附件，可多次调用该方法添加多个附件
                        message.addAttachment(fileName, file);
                    }
                } else {
                    message.setText(emailContentCondition.getText());
                }


            }
        };
        return preparator;
    }

    @Override
    public void sendEmail(EmailSetttingPo emailSetttingPo, EmailContentCondition emailContentCondition) {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        //yangjun@bwda.net
        javaMailSender.setUsername(emailSetttingPo.getAddress());
        //"smtp.exmail.qq.com"
        javaMailSender.setHost(emailSetttingPo.getEmailServerCode());
        javaMailSender.setPassword(emailSetttingPo.getPassword());
        javaMailSender.setPort(Integer.parseInt(emailSetttingPo.getPort()));
        javaMailSender.setDefaultEncoding("UTF-8");
        javaMailSender.send(send(emailSetttingPo, emailContentCondition));
        System.out.println("发送成功！");

    }
}